#!/bin/bash
#
# startup
#
# Called from rc.local to start FPP
#
#

BINDIR=$(cd $(dirname $0) && pwd)

. ${BINDIR}/common
. ${BINDIR}/functions

teeOutput

echo "FPP - Setting up for the Falcon Player on the ${FPPPLATFORM} platform"
checkTimeAgainstUSNO

# Print/Say the IP address
WaitForInterfacesUp

_IP=$(hostname -I) || true
if [ "$_IP" ]; then
	echo "FPP - Found IP(s): $_IP"

	DISABLEIPANN=$(getSetting disableIPAnnouncement)
	if [ "x${DISABLEIPANN}" != "x1" ]
	then
		arrHost=(${_IP// / })
		FLITESTR="I Have Found The Following I P Addresses, ${arrHost[0]}, ${arrHost[1]},  ${arrHost[2]}"
		if [ "${FPPPLATFORM}" = "BeagleBone Black" ]
		then
			(flite -voice awb -o /var/tmp/flite.wav "${FLITESTR}" && mplayer -ao alsa /var/tmp/flite.wav) &
		else
			flite -voice awb "${FLITESTR}" &
		fi
	fi
else
  echo "FPP - No IP(s) found"
fi

# this is done at image creation on BeagleBone
if [ "${FPPPLATFORM}" != "BeagleBone Black" ]
then
    echo "FPP - Copying rsync daemon config files into place and restarting"
    sed -e "s#FPPDIR#${FPPDIR}#g" -e "s#FPPHOME#${FPPHOME}#g" -e "s#FPPUSER#${FPPUSER}#g" < ${FPPDIR}/etc/rsync > /etc/default/rsync
    sed -e "s#FPPDIR#${FPPDIR}#g" -e "s#FPPHOME#${FPPHOME}#g" -e "s#FPPUSER#${FPPUSER}#g" < ${FPPDIR}/etc/rsyncd.conf > /etc/rsyncd.conf
    /etc/init.d/rsync restart

    if dpkg --get-selections | grep -qc -e ^apache2\    ; then
    echo "FPP - Copying Apache config into place and restarting Apache"
    sed -e "s#FPPDIR#${FPPDIR}#g" -e "s#FPPHOME#${FPPHOME}#g" < ${FPPDIR}/etc/apache2.site > ${SITEFILE}
    case "${OSVER}" in
        debian_7)
            /etc/init.d/apache2 restart
            ;;
        debian_8|debian_9)
            systemctl restart nginx.service
            ;;
    esac
    else
    echo "FPP - Copying nginx config into place and restarting nginx"
    sed -e "s#FPPDIR#${FPPDIR}#g" -e "s#FPPHOME#${FPPHOME}#g" < ${FPPDIR}/etc/nginx.conf > ${NGINX_SITEFILE}
    case "${OSVER}" in
        debian_7)
            /etc/init.d/nginx restart
            ;;
        debian_8)
            systemctl restart nginx.service
            ;;
        debian_9)
            sed -i "s#php5-fpm#php/php7.0-fpm#" ${NGINX_SITEFILE}
            systemctl restart nginx.service
            ;;
    esac
    fi

#echo "FPP - Copying Nginx config into place and restarting Nginx"
#mkdir /var/log/nginx
#chown www-data /var/log/nginx
#sed -e "s#FPPDIR#${FPPDIR}#g" -e "s#FPPHOME#${FPPHOME}#g" < ${FPPDIR}/etc/nginx.conf > /etc/nginx/sites-available/default
#/etc/init.d/nginx restart
fi

echo "FPP - Starting FPP boot script"
${BINDIR}/fpp_boot

##############################################################################
# Leave these things till last so user can see output of anything above here
##############################################################################
applyScreenBlankSetting

if [ "$_IP" ]; then
  echo "FPP - Found IP(s): $_IP"
fi

